package br.com.sovi.mobile.j2me.gps;

import javax.microedition.location.Location;

/**
 *
 * @author Realm
 */
public class UpdateHandler implements Runnable {

    private Location updatedLocation = null;
    private UpdateListener updateListener;
    private boolean running = true;

    public UpdateHandler(UpdateListener updateListener) {
        this.updateListener = updateListener;
    }

    public void stop() {
        running = false;
    }

    // The run method performs the actual processing of the location
    // updates
    public void run() {
        Location locationToBeHandled = null;
        while (running) {
            synchronized (this) {
                if (updatedLocation == null) {
                    try {
                        wait();
                    } catch (Exception e) {
                    }
                }
                locationToBeHandled = updatedLocation;
                updatedLocation = null;
            }

            // The benefit of the MessageListener is here.
            // This thread could via similar triggers be
            // handling other kind of events as well in
            // addition to just receiving the location updates.
            if (locationToBeHandled != null) {
                processUpdate(locationToBeHandled);
            }
        }
    }

    public synchronized void handleUpdate(Location update) {
        updatedLocation = update;
        notify();
    }

    private void processUpdate(Location update) {
        updateListener.updated(update);
    }
}
